<?php
namespace app\home\controller;

use think\Controller;
/**
 * 授权控制器
 * Class Openid
 * @package app\home\controller
 */
class Openid extends Controller
{
    protected $appid;
    protected $secret;
    function __construct($appid,$secret)
    {
        $this->appid = $appid;
        $this->secret = $secret;
    }
    // 网页授权登录获取 OpendId
    public function auth_user() {
        if(!isset($_GET['code'])){
            $baseUrl = urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING']);
            $this->redirect('https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->appid.'&redirect_uri='.$baseUrl.'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect',302);
        }else{
            $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->appid.'&secret='.$this->secret.'&code=' . $_GET['code'] . '&grant_type=authorization_code';
            $info = file_get_contents($url);//发送HTTPs请求并获取返回的数据，推荐使用curl
            $json = json_decode($info);//对json数据解码
            $arr = get_object_vars($json);
            if (empty($arr['access_token'])) {
                return admin_json('-1', $arr['errmsg']);
            }
            $access_token = $arr['access_token'];
            $openid = $arr['openid'];
            $user_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
            $user_info = file_get_contents($user_url);//发送HTTPs请求并获取返回的数据，推荐使用curl
            $user_json = json_decode($user_info);//对json数据解码
            $user_arr = get_object_vars($user_json);
            return $user_arr;
        }
    }
}